<template>
  <div>
    <h2>商品库存管理</h2>
    <!-- 搜索表单 -->
    <div class="search-form">
      <el-input v-model="searchForm.productName" placeholder="商品名称"></el-input>
      <!-- 商品售价范围 -->
      <el-input v-model="searchForm.priceMin" placeholder="最低售价"></el-input>
      <el-input v-model="searchForm.priceMax" placeholder="最高售价"></el-input>
      <!-- 商品进价范围 -->
      <el-input v-model="searchForm.purchasePriceMin" placeholder="最低进价"></el-input>
      <el-input v-model="searchForm.purchasePriceMax" placeholder="最高进价"></el-input>
      <!-- 商品库存范围 -->
      <el-input v-model="searchForm.stockMin" placeholder="库存最小值"></el-input>
      <el-input v-model="searchForm.stockMax" placeholder="库存最大值"></el-input>
      <el-button class="blue-button" @click="fetchProductList">查询</el-button>
      <el-button class="red-button" @click="clearSearchForm">清空条件</el-button>
    </div>
    <!-- 商品列表表格 -->
    <el-table
      :data="productList"
      stripe
      hover-effect
      border
      style="width: 100%">
      <el-table-column prop="productId" label="商品 ID"></el-table-column>
      <el-table-column prop="productName" label="商品名称"></el-table-column>
      <el-table-column prop="productUnit" label="商品单位"></el-table-column> <!-- 新增单位列 -->
      <el-table-column prop="stock" label="商品库存"></el-table-column>
      <el-table-column prop="price" label="售价">
        <template #default="scope">
          <span v-if="scope.row.price">{{ scope.row.price }}</span>
          <el-button 
            v-else 
            v-if="userInfo.userRole === 0" 
            @click="openPricingDialog(scope.row)" 
            type="primary">
            去定价
          </el-button>
        </template>
      </el-table-column>
      <el-table-column prop="purchasePrice" label="进价"></el-table-column>
    </el-table>
    <!-- 分页组件 -->
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="currentPage"
      :page-sizes="[10, 20, 30]"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total">
    </el-pagination>

    <!-- 定价对话框 -->
    <el-dialog v-model="pricingDialogVisible" title="商品定价" @close="closePricingDialog">
      <el-form :model="pricingForm" :rules="pricingRules" ref="pricingFormRef">
        <el-form-item label="商品名称" :label-width="formLabelWidth">
          <span>{{ pricingProduct.productName }}</span>
        </el-form-item>
        <el-form-item label="售价" prop="price" :label-width="formLabelWidth">
          <el-input v-model.number="pricingForm.price"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="closePricingDialog">取消</el-button>
        <el-button type="primary" @click="submitPricingForm">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, defineProps } from 'vue';
import request from '../utils/request'; 
import { ElPagination, ElInput, ElButton, ElTable, ElTableColumn, ElDialog, ElForm, ElFormItem, ElMessage } from 'element-plus';

// 接收父组件传递的用户信息
const props = defineProps({
  userInfo: {
    type: Object,
    default: () => ({ isAdmin: false })
  }
});

const productList = ref([]);
const currentPage = ref(1); 
const pageSize = ref(10); 
const total = ref(0); 
const searchForm = ref({
  page: currentPage.value,
  pageSize: pageSize.value,
  productName: '',
  priceMin: '',
  priceMax: '',
  purchasePriceMin: '',
  purchasePriceMax: '',
  stockMin: '',
  stockMax: ''
});

const pricingDialogVisible = ref(false);
const pricingProduct = ref({});
const pricingForm = ref({ price: '' });
const pricingFormRef = ref(null);
const formLabelWidth = ref('80px');
const pricingRules = {
  price: [
    { required: true, message: '请输入售价', trigger: 'blur' },
    { type: 'number', message: '售价必须为数字', trigger: 'blur' }
  ]
};

const fetchProductList = async () => {
  try {
    searchForm.value.page = currentPage.value;
    searchForm.value.pageSize = pageSize.value;
    const response = await request.get('/product/getProducts', {
      params: searchForm.value
    });
    productList.value = response.data.list;
    total.value = response.data.total;
  } catch (error) {
    console.error('获取商品列表失败:', error);
  }
};

const handleSizeChange = (newSize) => {
  pageSize.value = newSize;
  fetchProductList();
};

const handleCurrentChange = (newPage) => {
  currentPage.value = newPage;
  fetchProductList();
};

const clearSearchForm = () => {
  searchForm.value = {
    page: 1,
    pageSize: 10,
    productName: '',
    priceMin: '',
    priceMax: '',
    purchasePriceMin: '',
    purchasePriceMax: '',
    stockMin: '',
    stockMax: ''
  };
  currentPage.value = 1;
  pageSize.value = 10;
  fetchProductList();
};

const openPricingDialog = (product) => {
  pricingProduct.value = product;
  pricingForm.value.price = '';
  pricingDialogVisible.value = true;
};

const closePricingDialog = () => {
  pricingDialogVisible.value = false;
};

const submitPricingForm = async () => {
  pricingFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        const productId = pricingProduct.value.productId;
        const price = pricingForm.value.price;
        const response = await request.put(`/product/updatePrice?productId=${productId}&price=${price}`);
        if (response.code === 1) {
          ElMessage.success('定价成功');
          closePricingDialog();
          fetchProductList();
        } else {
          ElMessage.error('定价失败');
          console.error('定价失败:', response.data.message);
        }
      } catch (error) {
        ElMessage.error('定价失败');
        console.error('定价失败:', error);
      }
    }
  });
};

onMounted(() => {
  fetchProductList();
});
</script>

<style scoped>
.search-form {
  display: flex;
  gap: 5px;
  margin-bottom: 20px;
  align-items: center;
  flex-wrap: nowrap;
  overflow-x: auto;
}

.search-form > el-input {
  flex: 0 0 120px;
  min-width: 0;
}

.search-form > el-button {
  flex: 0 0 auto;
}

.red-button {
  background-color: #f5222d; /* 红色背景色 */
  color: #fff; /* 白色文字颜色 */
  border: none;
  transition: background-color 0.3s; /* 添加过渡效果，使鼠标悬停时颜色变化更平滑 */
}
.blue-button{
  background-color: #00bfff; /* 蓝色背景色 */
  color: #fff; /* 白色文字颜色 */
  border: none;
  transition: background-color 0.3s; /* 添加过渡效果，使鼠标悬停时颜色变化更平滑 */
}

.red-button:hover {
  background-color: #cf1322; /* 鼠标悬停时的背景色，颜色加深 */
}
.blue-button:hover {
  background-color: #009acd; /* 鼠标悬停时蓝色按钮背景色加深 */
}
</style>